from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, TextAreaField, FileField, SubmitField, BooleanField, PasswordField
from wtforms.validators import DataRequired, Length, Optional, NumberRange, Email, ValidationError
from ..models import User

class CoupleForm(FlaskForm):
    season = IntegerField('季数', validators=[DataRequired()])
    
    husband_name = StringField('丈夫姓名', validators=[DataRequired(), Length(max=64)])
    husband_age = IntegerField('丈夫年龄', validators=[DataRequired()])
    husband_occupation = StringField('丈夫职业', validators=[Optional(), Length(max=64)])
    husband_avatar = FileField('丈夫头像')
    
    wife_name = StringField('妻子姓名', validators=[DataRequired(), Length(max=64)])
    wife_age = IntegerField('妻子年龄', validators=[DataRequired()])
    wife_occupation = StringField('妻子职业', validators=[Optional(), Length(max=64)])
    wife_avatar = FileField('妻子头像')
    
    marriage_years = IntegerField('结婚年限', validators=[DataRequired()])
    story = TextAreaField('故事简介', validators=[Optional()])
    
    submit = SubmitField('提交')

class QuoteForm(FlaskForm):
    content = TextAreaField('名言内容', validators=[DataRequired()])
    author = StringField('作者', validators=[Optional(), Length(max=64)])
    is_active = BooleanField('是否启用')
    submit = SubmitField('提交')

class UserEditForm(FlaskForm):
    username = StringField('用户名', validators=[DataRequired(), Length(min=2, max=20)])
    email = StringField('邮箱', validators=[DataRequired(), Email()])
    password = PasswordField('密码', validators=[Optional(), Length(min=6)])
    is_admin = BooleanField('管理员权限')
    submit = SubmitField('保存修改')

    def __init__(self, original_username=None, original_email=None, *args, **kwargs):
        super(UserEditForm, self).__init__(*args, **kwargs)
        self.original_username = original_username
        self.original_email = original_email

    def validate_username(self, field):
        if field.data != self.original_username:
            user = User.query.filter_by(username=field.data).first()
            if user:
                raise ValidationError('该用户名已被使用')

    def validate_email(self, field):
        if field.data != self.original_email:
            user = User.query.filter_by(email=field.data).first()
            if user:
                raise ValidationError('该邮箱已被注册')
  